/**
 * 
 */
package com.swim.natatoriuminfo.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.swim.natatoriuminfo.entity.NatatoriumInfo;

import com.swim.natatoriuminfo.dao.NatatoriumInfoDao;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.file.utils.FileUploadUtils;

/**
 * 游泳馆信息Service
 * @author tql
 * @version 2021-03-14
 */
@Service
@Transactional(readOnly=true)
public class NatatoriumInfoService extends CrudService<NatatoriumInfoDao, NatatoriumInfo> {
	
	@Value("${server.context-path}")
	private String contextPath;
	
	/**
	 * 获取单条数据
	 * @param natatoriumInfo
	 * @return
	 */
	@Override
	public NatatoriumInfo get(NatatoriumInfo natatoriumInfo) {
		NatatoriumInfo result = super.get(natatoriumInfo);
		if (result != null) {
			//获取客服微信二维码图片
			List<FileUpload> fileUploadList = FileUploadUtils.findFileUpload(result.getId(), "customer_wechat_image");
			if (!CollectionUtils.isEmpty(fileUploadList)) {
				for (FileUpload fileUploadListOne : fileUploadList) {
					result.setCustomerWechatImageUrl(contextPath + "/userfiles/fileupload/" + fileUploadListOne.getFileEntity().getFilePath() + fileUploadListOne.getFileEntity().getFileId() + "." + fileUploadListOne.getFileEntity().getFileExtension());
					break;
				}
			}
//			//获取游泳馆图片
//			List<FileUpload> fileUploadList1 = FileUploadUtils.findFileUpload(result.getId(), "natatoriumInfo_image");
//			if (!CollectionUtils.isEmpty(fileUploadList1)) {
//				List<String> natatoriumInfoImageUrlList = new ArrayList<String>();	//游泳馆图片url集合
//				for (FileUpload fileUploadListOne : fileUploadList1) {
//					natatoriumInfoImageUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.getFileEntity().getFilePath() + fileUploadListOne.getFileEntity().getFileId() + "." + fileUploadListOne.getFileEntity().getFileExtension());
//				}
//				result.setNatatoriumInfoImageUrlList(natatoriumInfoImageUrlList);
//			}
			//获取环境视频
			List<FileUpload> fileUploadMediaList = FileUploadUtils.findFileUpload(result.getId(), "natatoriumInfo_media");
			if (!CollectionUtils.isEmpty(fileUploadMediaList)) {
				List<String> natatoriumInfoMediaUrlList = new ArrayList<String>();	//环境视频url集合
				for (FileUpload fileUploadListOne : fileUploadMediaList) {
					natatoriumInfoMediaUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.getFileEntity().getFilePath() + fileUploadListOne.getFileEntity().getFileId() + "." + fileUploadListOne.getFileEntity().getFileExtension());
				}
				result.setNatatoriumInfoMediaUrlList(natatoriumInfoMediaUrlList);
			}
			//获取运动实拍图片
			List<FileUpload> fileUploadList1 = FileUploadUtils.findFileUpload(result.getId(), "movement_image");
			if (!CollectionUtils.isEmpty(fileUploadList1)) {
				List<String> movementImageUrlList = new ArrayList<String>();	//运动实拍图片url集合
				for (FileUpload fileUploadListOne : fileUploadList1) {
					movementImageUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.getFileEntity().getFilePath() + fileUploadListOne.getFileEntity().getFileId() + "." + fileUploadListOne.getFileEntity().getFileExtension());
				}
				result.setMovementImageUrlList(movementImageUrlList);
			}
			//获取其它图片（暂时包含之前的游泳馆图片）
			List<FileUpload> fileUploadList2 = FileUploadUtils.findFileUpload(result.getId(), "other_image");
			List<String> otherImageUrlList = new ArrayList<String>();	//其它图片url集合
			if (!CollectionUtils.isEmpty(fileUploadList2)) {
				for (FileUpload fileUploadListOne : fileUploadList2) {
					otherImageUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.getFileEntity().getFilePath() + fileUploadListOne.getFileEntity().getFileId() + "." + fileUploadListOne.getFileEntity().getFileExtension());
				}
			}
				//获取游泳馆图片
				List<FileUpload> fileUploadList3 = FileUploadUtils.findFileUpload(result.getId(), "natatoriumInfo_image");
				if (!CollectionUtils.isEmpty(fileUploadList3)) {
					for (FileUpload fileUploadListOne : fileUploadList3) {
						otherImageUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.getFileEntity().getFilePath() + fileUploadListOne.getFileEntity().getFileId() + "." + fileUploadListOne.getFileEntity().getFileExtension());
					}
				}
			result.setOtherImageUrlList(otherImageUrlList);
		}
		return result;
	}
	
	/**
	 * 查询分页数据
	 * @param page 分页对象
	 * @param natatoriumInfo
	 * @return
	 */
	@Override
	public Page<NatatoriumInfo> findPage(Page<NatatoriumInfo> page, NatatoriumInfo natatoriumInfo) {
		Page<NatatoriumInfo> pageList = super.findPage(page, natatoriumInfo);
		List<NatatoriumInfo> natatoriumInfoList = pageList.getList();
		if (!CollectionUtils.isEmpty(natatoriumInfoList)) {
			for (NatatoriumInfo natatoriumInfoOne : natatoriumInfoList) {
				//获取游泳馆图片
				List<FileUpload> fileUploadListOne = FileUploadUtils.findFileUpload(natatoriumInfoOne.getId(), "natatoriumInfo_image");
				if (!CollectionUtils.isEmpty(fileUploadListOne)) {
					List<String> natatoriumInfoImageUrlList = new ArrayList<String>();	//游泳馆图片url集合
					natatoriumInfoImageUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.get(0).getFileEntity().getFilePath() + fileUploadListOne.get(0).getFileEntity().getFileId() + "." + fileUploadListOne.get(0).getFileEntity().getFileExtension());
					natatoriumInfoOne.setNatatoriumInfoImageUrlList(natatoriumInfoImageUrlList);
				}
			}
		}
		pageList.setList(natatoriumInfoList);
		return pageList;
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param natatoriumInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(NatatoriumInfo natatoriumInfo) {
		super.save(natatoriumInfo);
		// 保存客服微信二维码
		FileUploadUtils.saveFileUpload(natatoriumInfo.getId(), "customer_wechat_image");
		// 保存列表大图
		FileUploadUtils.saveFileUpload(natatoriumInfo.getId(), "natatoriumInfo_image");
		// 保存运动实拍图片
		FileUploadUtils.saveFileUpload(natatoriumInfo.getId(), "movement_image");
		// 保存其它图片
		FileUploadUtils.saveFileUpload(natatoriumInfo.getId(), "other_image");
		// 保存环境视频文件
		FileUploadUtils.saveFileUpload(natatoriumInfo.getId(), "natatoriumInfo_media");
	}
	
	/**
	 * 更新状态
	 * @param natatoriumInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(NatatoriumInfo natatoriumInfo) {
		super.updateStatus(natatoriumInfo);
	}
	
	/**
	 * 删除数据
	 * @param natatoriumInfo
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(NatatoriumInfo natatoriumInfo) {
		super.delete(natatoriumInfo);
	}
	
	/**
	 * 查询附近场馆（按区域，星级评分选择6家）
	 * @param natatoriumInfoId 游泳馆id
	 * @return List<NatatoriumInfo> 
	 */
	public List<NatatoriumInfo> findNearNatatoriumList(String natatoriumInfoId) {
		NatatoriumInfo natatoriumInfo = super.get(natatoriumInfoId);
		NatatoriumInfo natatoriumInfoWhere = new NatatoriumInfo();
		natatoriumInfoWhere.setArea(natatoriumInfo.getArea());
		natatoriumInfoWhere.setPage(new Page<>(1, 6));
		natatoriumInfoWhere.getPage().setOrderBy("start_level_score desc");
		Page<NatatoriumInfo> page = super.findPage(natatoriumInfoWhere);
		List<NatatoriumInfo> natatoriumInfoList = page.getList();
		if (!CollectionUtils.isEmpty(natatoriumInfoList)) {
			for (NatatoriumInfo natatoriumInfoOne : natatoriumInfoList) {
				//获取游泳馆图片
				List<FileUpload> fileUploadListOne = FileUploadUtils.findFileUpload(natatoriumInfoOne.getId(), "natatoriumInfo_image");
				if (!CollectionUtils.isEmpty(fileUploadListOne)) {
					List<String> natatoriumInfoImageUrlList = new ArrayList<String>();	//游泳馆图片url集合
					natatoriumInfoImageUrlList.add(contextPath + "/userfiles/fileupload/" + fileUploadListOne.get(0).getFileEntity().getFilePath() + fileUploadListOne.get(0).getFileEntity().getFileId() + "." + fileUploadListOne.get(0).getFileEntity().getFileExtension());
					natatoriumInfoOne.setNatatoriumInfoImageUrlList(natatoriumInfoImageUrlList);
				}
			}
		}
		return natatoriumInfoList;
	}
	
	/**
	 * 查询区域对应的场馆数量
	 */
	public Map<String, Long> findNatatoriumNum() {
		Map<String, Long> map = new HashMap<String, Long>();
		List<NatatoriumInfo> natatoriumInfoList = super.findList(new NatatoriumInfo());
		if (CollectionUtils.isNotEmpty(natatoriumInfoList)) {
			map = natatoriumInfoList.stream().collect(Collectors.groupingBy(item -> item.getArea(), Collectors.counting()));
		}
		return map;
	}
	
//	/**
//	 * 获取场馆预约电话
//	 * @param natatoriumInfoId 游泳馆id
//	 * @return String 预约电话
//	 */
//	public String getReservationPhone(String natatoriumInfoId) {
//		String reservationPhone = "";
//		NatatoriumInfo natatoriumInfo = super.get(natatoriumInfoId);
//		
//        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
//                .accessKeyId("LTAI5tLC3W2xujCDxcVisHTA")
//                .accessKeySecret("gfPc4HfqU2hpkBeuYczPLUC630bpcB")
//                //.securityToken("<your-token>") // use STS token
//                .build());
//
//        // Configure the Client
//        AsyncClient client = AsyncClient.builder()
//                .region("undefined") // Region ID
//                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
//                .credentialsProvider(provider)
//                //.serviceConfiguration(Configuration.create()) // Service-level configuration
//                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
//                .overrideConfiguration(
//                        ClientOverrideConfiguration.create()
//                                .setEndpointOverride("dyplsapi.aliyuncs.com")
//                        //.setConnectTimeout(Duration.ofSeconds(30))
//                )
//                .build();
//
//        // Parameter settings for API request
//        AddAxnTrackNoRequest addAxnTrackNoRequest = AddAxnTrackNoRequest.builder()
//                .poolKey("your_value")
//                .phoneNoX("your_value")
//                // Request-level configuration rewrite, can set Http request parameters, etc.
//                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
//                .build();
//
//        // Asynchronously get the return value of the API request
//        CompletableFuture<AddAxnTrackNoResponse> response = client.addAxnTrackNo(addAxnTrackNoRequest);
//        // Synchronously get the return value of the API request
//        AddAxnTrackNoResponse resp = null;
//		try {
//			resp = response.get();
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (ExecutionException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//        System.out.println(new Gson().toJson(resp));
//        // Asynchronous processing of return values
//        /*response.thenAccept(resp -> {
//            System.out.println(new Gson().toJson(resp));
//        }).exceptionally(throwable -> { // Handling exceptions
//            System.out.println(throwable.getMessage());
//            return null;
//        });*/
//
//        // Finally, close the client
//        client.close();
//		return reservationPhone;
//	}
}